#-*- encoding:utf-8 -*-
import web
from configs import db as DB
from configs import auto_reload_configs as AUTOLOAD

class BaseModel(object):
    table = ''
    db = DB

    def findCount(self, conditions):
        record = self.find(conditions, 'count(*) as count')
        if record:
            return record.count
        return 0

    def findAll(self, conditions=None, fields='*', limit=None, offset=None, orderby=None):
        if not conditions:
            conditions = {}

        return self.db.where(
                self.table,what=fields, order=orderby, group=None, limit=limit, 
                offset=offset, **conditions)


    def find(self, conditions, fields='*'):
        record = self.findAll(conditions, fields)
        if record:
            return record[0]
        return None

    def findById(self, id=None, fields='*'):
        return self.find(dict(id=id), fields)

    def delete(self,id):
        return self.db.delete(self.table, vars=dict(id=id), where = 'id=$id')

    def add(self,data):
        success,msg = True, '保存成功'
        self.db.insert(self.table,**data)
        return success,msg

    def update(self,conditions,data):
        if not conditions:
            return False,'更新失败'

        where = ' and '.join(['%s=$%s' % (item,item) for item in conditions.keys()])
        self.db.update(self.table, where, conditions,**data)
        return  True, '更新成功'

class PostModel(BaseModel):
    table = 'posts'

    def update(self, data):
        data['modified'] = web.SQLLiteral('now()',)
        conditions = dict(id=data.id)
        return super(PostModel, self).update(conditions,data)

    def add(self, data):
        data['created'] = web.SQLLiteral('now()',)
        data['modified'] = web.SQLLiteral('now()',)
        return super(PostModel, self).add(data)

    def findAll(self, conditions, fields='*', limit=None, offset=None,orderby='created desc'):
        return super(PostModel, self).findAll(conditions,fields,limit,offset,orderby)

    def latest(self,fields='id,title,created,content',limit=5):
        return self.findAll(dict(status='published'),fields,limit)

postModel = PostModel()

class SettingModel(BaseModel):
    table = 'settings'

    def save(self,data):
        if not data:
            return False

        for item in data:
            conditions = dict(name=item)
            config = dict(name=item,value=data.get(item))
            if self.findCount(conditions):
                self.update(conditions,config)
            else:
                if item in AUTOLOAD:
                    config['autoload'] = 1
                self.add(config)

        return True,'保存配置成功'

    def auth(self,password):
        return self.findCount(dict(name='password',value=password))

    def autloads(self):
        data = self.findAll(dict(autoload=1),'name,value')
        if len(data):
            return {item['name']:item['value'] for item in data}
        return {}

    def getConfig(self, name, default=None):
        config = self.find(dict(name=name),'value')
        if config:
            return config['value']
        return default

settingModel = SettingModel()